package user

import (
	"context"
	"errors"
	"log"

	pb "gitee.com/jiebaiyou/demo-grpc/protos/user/v2"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

type Client struct {
	client pb.UserServiceClient
}

func NewClient(addr string) *Client {
	log.Printf("Attempting to connect to user service at %s", addr)
	conn, err := grpc.NewClient(
		addr,
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy":"round_robin"}`),
	)
	if err != nil {
		log.Fatalf("Failed to connect to user service: %v", err)
	}
	log.Printf("Successfully connected to user service")
	return &Client{client: pb.NewUserServiceClient(conn)}
}

func (c *Client) Create(ctx context.Context, req *pb.CreateRequest) (*pb.CreateResponse, error) {
	resp, err := c.client.Create(ctx, req)
	if err != nil {
		log.Printf("could not create user: %v", err)
		return nil, errors.New("could not create user")
	}
	return resp, nil
}

func (c *Client) Get(ctx context.Context, req *pb.GetRequest) (*pb.GetResponse, error) {
	resp, err := c.client.Get(ctx, req)
	if err != nil {
		log.Printf("could not get user: %v", err)
		return nil, errors.New("could not get user")
	}
	return resp, nil
}
